﻿using Lightworks.Core.Constant;
using Lightworks.System.Dto;
using Lightworks.System.Models;
using Lightworks.System.Services;
using Microsoft.AspNetCore.Mvc;

namespace Lightworks.Api.Controllers
{
    [ApiController]
    [Route("api/system/user")]
    public class UserController : ApiBaseController
    {
        IUserService userService;
        private readonly ILogger<UserController> logger;
        public UserController(ILogger<UserController> logger, IUserService userService) 
        {
            this.logger = logger;
            this.userService = userService;
        }

        [HttpPost("create")]
        public ApiResult Create(AddUserReq user) 
        {
            var id = userService.Create(user);
            if (id == 0) 
            {
                return Error("有用户在使用该角色，不允许删除");
            }
            return Ok(id);
        }

        [HttpGet("list")]
        public ApiResult List([FromQuery]UserSearchReq req) 
        {
            var data = userService.GetUserList(req);
            return Ok(data);
        }

        [HttpPost("save")]
        public ApiResult Save(UpdateUserReq user) 
        {
            try 
            {
                userService.Save(user);
                return Ok(user.Id);
            }
            catch (Exception ex) 
            {
                logger.LogError(ex.Message, ex);
                return Error("保存失败");
            }
        }

        [HttpPost("delete")]
        public ApiResult Delete(long[] ids) 
        {
            if (userService.Delete(ids)) {
                return Ok();
            }
            return Error();
        }
    }
}
